import { app, BrowserWindow, ipcMain, screen } from 'electron'
import * as path from 'path'
import * as fs from 'fs'
import { platform } from 'os'
// 使用require语法导入electron-store
const Store = require('electron-store')
const { execSync, exec } = require('child_process')
// 移除win32-api依赖，使用Electron原生API
// 配置electron-store
const store = new Store({
  name: 'chrome-manager-settings',
  defaults: {
    chromePath: '',
    dataDir: '',
    shortcutDir: '',
    windowSize: { width: 1200, height: 800 },
    debug: false
  }
})

// 全局变量确保只创建一个窗口实例
let mainWindow: BrowserWindow | null = null
let windowCreated = false

// 等待开发服务器就绪
async function waitForServer(url: string, maxRetries = 5, retryDelay = 500): Promise<void> {
  const { net } = require('electron')
  
  for (let i = 0; i < maxRetries; i++) {
    try {
      console.log(`检查开发服务器状态... (${i + 1}/${maxRetries}) - ${url}`)
      
      return new Promise((resolve, reject) => {
        const request = net.request({
          method: 'GET',
          url: url
        })
        
        const timeout = setTimeout(() => {
          request.abort()
          if (i === maxRetries - 1) {
            reject(new Error('开发服务器连接超时'))
          } else {
            console.log(`开发服务器未就绪，${retryDelay}ms后重试...`)
            setTimeout(() => {
              waitForServer(url, maxRetries - i - 1, retryDelay).then(resolve).catch(reject)
            }, retryDelay)
          }
        }, 2000)
        
        request.on('response', (response: any) => {
          clearTimeout(timeout)
          console.log(`开发服务器已就绪 - 状态码: ${response.statusCode}`)
          resolve()
        })
        
        request.on('error', (error: any) => {
          clearTimeout(timeout)
          console.log(`开发服务器连接失败: ${error.message}`)
          if (i === maxRetries - 1) {
            reject(new Error(`开发服务器未就绪: ${error.message}`))
          } else {
            console.log(`${retryDelay}ms后重试...`)
            setTimeout(() => {
              waitForServer(url, maxRetries - i - 1, retryDelay).then(resolve).catch(reject)
            }, retryDelay)
          }
        })
        
        request.end()
      })
    } catch (error) {
      console.log(`等待开发服务器启动时出错: ${error}`)
      if (i === maxRetries - 1) {
        throw error
      }
      console.log(`等待开发服务器启动... (${i + 1}/${maxRetries})`)
      await new Promise(resolve => setTimeout(resolve, retryDelay))
    }
  }
}

// 创建主窗口
function createMainWindow() {
  // 如果窗口已经创建，则不重复创建
  if (windowCreated) {
    console.log('Window already created, skipping...')
    return
  }
  
  const { width, height } = store.get('windowSize') as { width: number; height: number }
  
  mainWindow = new BrowserWindow({
    width,
    height,
    title: 'Chrome Manager',
    show: false, // 先不显示窗口，避免闪烁
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js'),
      nodeIntegration: false,
      contextIsolation: true,
      sandbox: false,
      webSecurity: false, // 开发模式下禁用web安全
      allowRunningInsecureContent: true // 允许不安全内容
    }
  })
  
  // 设置窗口创建标志
  windowCreated = true

  // 设置控制台编码，确保中文正确输出
  if (process.platform === 'win32') {
    // 对于Windows平台，尝试设置输出编码
    try {
      // 确保控制台使用UTF-8编码
      process.stdout.write('\u001b[?65;1;4;15h'); // 设置控制台模式
    } catch (e) {
      // 忽略错误，某些环境下可能不支持
    }
  }

  // 加载URL
  // 强制开发模式检测 - 直接检查环境变量是否存在
  console.log('=== 环境变量检查 ===')
  console.log('NODE_ENV=', process.env.NODE_ENV)
  console.log('VITE_DEV_SERVER_URL=', process.env.VITE_DEV_SERVER_URL)
  console.log('==================')
  
  // 使用简单的开发模式检测逻辑
  const devUrl = process.env.VITE_DEV_SERVER_URL || 'http://localhost:3000'
  
  // 显示加载页面
  const showLoadingPage = () => {
    const loadingHTML = `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <title>Chrome Manager - 加载中</title>
        <style>
          body {
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            color: white;
          }
          .loading-container {
            text-align: center;
          }
          .loading-spinner {
            width: 50px;
            height: 50px;
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-top: 4px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
          }
          @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
          }
          h1 {
            margin: 0 0 10px 0;
            font-size: 24px;
            font-weight: 300;
          }
          p {
            margin: 0;
            opacity: 0.8;
            font-size: 14px;
          }
        </style>
      </head>
      <body>
        <div class="loading-container">
          <div class="loading-spinner"></div>
          <h1>Chrome Manager</h1>
          <p>正在加载应用...</p>
        </div>
      </body>
      </html>
    `
    mainWindow!.loadURL(`data:text/html,${encodeURIComponent(loadingHTML)}`)
  }

  // 等待开发服务器启动
  const loadApp = async () => {
    try {
  if (devUrl) {
        // 先显示加载页面
        showLoadingPage()
        
    // 只要设置了VITE_DEV_SERVER_URL，就认为是开发模式
    console.log('开发模式: 加载', devUrl)
    console.log('中文日志测试: 开发服务器连接中...')
        
        try {
          // 等待开发服务器就绪
          await waitForServer(devUrl)
        } catch (serverError) {
          console.warn('开发服务器检查失败，等待 3 秒后重试:', serverError)
          await new Promise(resolve => setTimeout(resolve, 3000))
        }
        
        try {
          await mainWindow!.loadURL(devUrl)
          console.log('应用加载完成')
          // 内容加载完成后显示窗口，避免闪烁
          mainWindow!.show()
        } catch (loadError) {
          console.error('加载 URL 失败，尝试重新加载:', loadError)
          // 等待 2 秒后重试
          await new Promise(resolve => setTimeout(resolve, 2000))
          await mainWindow!.loadURL(devUrl)
          // 重试后也显示窗口
          mainWindow!.show()
        }
    
    // 开发模式自动打开调试工具
    const debugMode = store.get('debug') as boolean
    if (debugMode) {
          mainWindow!.webContents.openDevTools()
    }
  } else {
      // 否则是生产模式
      console.log('生产模式: 加载本地文件')
        await mainWindow!.loadFile(path.join(__dirname, '../../dist/index.html'))
        // 生产模式也延迟显示窗口
        mainWindow!.show()
      }
    } catch (error) {
      console.error('加载应用失败:', error)
      // 如果加载失败，显示错误页面
      const errorHTML = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="UTF-8">
          <title>Chrome Manager - 错误</title>
          <style>
            body {
              margin: 0;
              padding: 20px;
              background: #f5f5f5;
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
              display: flex;
              justify-content: center;
              align-items: center;
              height: 100vh;
            }
            .error-container {
              background: white;
              padding: 40px;
              border-radius: 8px;
              box-shadow: 0 2px 10px rgba(0,0,0,0.1);
              text-align: center;
              max-width: 500px;
            }
            h1 { color: #e74c3c; margin-bottom: 20px; }
            p { color: #666; line-height: 1.6; }
          </style>
        </head>
        <body>
          <div class="error-container">
            <h1>加载失败</h1>
            <p>${error}</p>
          </div>
        </body>
        </html>
      `
      mainWindow!.loadURL(`data:text/html,${encodeURIComponent(errorHTML)}`)
    }
  }
  
  loadApp()

  // 窗口关闭事件
  mainWindow.on('closed', () => {
    mainWindow = null
    windowCreated = false // 重置标志，允许下次重新创建窗口
  })

  // 窗口大小变化事件
  mainWindow.on('resize', () => {
    if (mainWindow) {
      const { width, height } = mainWindow.getBounds()
      store.set('windowSize', { width, height })
    }
  })
}

// 获取Chrome窗口列表
// 获取保存的Chrome配置文件数据
async function getChromeProfiles() {
  try {
    // 获取配置中保存的数据目录
    const defaultDataDir = store.get('dataDir') || path.join(app.getPath('userData'), 'chrome-environments')
    
    const profiles: Array<{
      profileNumber: number,
      dataDir: string,
      shortcutPath?: string
    }> = []
    
    // 读取用户数据目录下的所有Profile文件夹
    if (fs.existsSync(defaultDataDir)) {
      try {
        const folders = fs.readdirSync(defaultDataDir, { withFileTypes: true })
        
        // 查找所有Profile_x格式的文件夹
        for (const folder of folders) {
          if (folder.isDirectory() && folder.name.startsWith('Profile_')) {
            const match = folder.name.match(/Profile_(\d+)/)
            if (match && match[1]) {
              const profileNumber = parseInt(match[1], 10)
              const profilePath = path.join(defaultDataDir, folder.name)
              
              // 检查是否存在Preferences文件来确认这是有效的Chrome配置文件
              const prefsPath = path.join(profilePath, 'Default', 'Preferences')
              if (fs.existsSync(prefsPath)) {
                // 检查数据目录内是否存在对应的快捷方式
                const shortcutPath = path.join(profilePath, `Profile_${profileNumber}.lnk`)
                
                profiles.push({
                  profileNumber,
                  dataDir: profilePath,
                  shortcutPath: fs.existsSync(shortcutPath) ? shortcutPath : undefined
                })
              }
            }
          }
        }
        
        // 按Profile编号排序
        profiles.sort((a, b) => a.profileNumber - b.profileNumber)
        
        console.log(`找到 ${profiles.length} 个创建的Chrome配置文件`)
      } catch (error) {
        console.error('读取配置文件目录失败:', error)
      }
    }
    
    return profiles
  } catch (error) {
    console.error('获取Chrome配置文件失败:', error)
    return []
  }
}

// 获取运行中的Chrome窗口信息
async function getRunningChromeWindows() {
  try {
    if (platform() !== 'win32') {
      console.log('当前非Windows平台，暂不支持获取Chrome窗口')
      return []
    }

    console.log('开始获取Chrome窗口信息...')
    const startTime = Date.now()

    // 获取保存的配置文件
    const profiles = await getChromeProfiles()
    
    // 获取所有运行中的Chrome进程信息
    let chromeProcesses = []
    
    try {
      // 使用单个PowerShell命令获取所有Chrome进程信息，避免多次调用
      const command = `powershell -ExecutionPolicy Bypass -Command "Get-WmiObject Win32_Process -Filter 'Name=\\"chrome.exe\\"' | Select-Object ProcessId, CommandLine | ConvertTo-Json"`
      console.log('执行PowerShell命令:', command)
      
      // 使用异步exec替代execSync，避免阻塞UI
      const output = await new Promise<string>((resolve, reject) => {
        exec(command, { encoding: 'utf8', timeout: 5000 }, (error: any, stdout: any, stderr: any) => {
          if (error) {
            reject(error)
          } else {
            resolve(stdout)
          }
        })
      })
      
      console.log('PowerShell输出:', output)
      
      // 解析JSON输出
      const processes = JSON.parse(output)
      console.log('解析的进程数据:', processes)
      
      // 确保processes是数组
      const processArray = Array.isArray(processes) ? processes : [processes]
      
      chromeProcesses = processArray.map((proc: any) => ({
        ProcessId: proc.ProcessId,
        CommandLine: proc.CommandLine || ''
      })).filter((proc: any) => proc.ProcessId && proc.CommandLine)
      
    } catch (error) {
      console.error('获取Chrome进程信息失败:', error)
      return []
    }
    
    // 过滤掉无效进程
    chromeProcesses = chromeProcesses.filter((proc: any) => proc.ProcessId && !isNaN(proc.ProcessId))
    
    // 准备结果数组
    const runningWindows = []
    
    // 遍历每个配置文件，检查是否有对应的Chrome进程在运行
    for (const profile of profiles) {
      // 查找匹配的进程
      const matchingProcess = chromeProcesses.find((proc: any) => {
        if (!proc.CommandLine) return false;
        
        // 使用正则表达式提取--user-data-dir参数值
        const userDataDirMatch = proc.CommandLine.match(/--user-data-dir=("[^"]+"|[^\s]+)/);
        if (userDataDirMatch && userDataDirMatch[1]) {
          // 去除可能的引号并标准化路径
          let processUserDataDir = userDataDirMatch[1].replace(/^"|"$/g, '');
          processUserDataDir = path.resolve(processUserDataDir);
          const profileDataDir = path.resolve(profile.dataDir);
          
          return processUserDataDir === profileDataDir;
        }
        return false;
      });
      
      if (matchingProcess) {
        const pid = matchingProcess.ProcessId
        
        // 尝试获取窗口信息 - 使用简单的PowerShell命令获取窗口句柄
        try {
          // 使用简单的PowerShell命令获取主窗口句柄
          const hwndCommand = `Get-Process -Id ${pid} | Select-Object -ExpandProperty MainWindowHandle`
          
          // 使用异步exec替代execSync
          const hwndOutput = await new Promise<string>((resolve, reject) => {
            exec(`powershell -ExecutionPolicy Bypass -Command "${hwndCommand}"`, { encoding: 'utf8' }, (error: any, stdout: any, stderr: any) => {
              if (error) {
                reject(error)
              } else {
                resolve(stdout.trim())
              }
            })
          })
          
          const hwnd = parseInt(hwndOutput) || 0
          
          if (hwnd > 0) {
            // 获取窗口标题
            const titleCommand = `Get-Process -Id ${pid} | Select-Object -ExpandProperty MainWindowTitle`
            
            // 使用异步exec替代execSync
            const titleOutput = await new Promise<string>((resolve, reject) => {
              exec(`powershell -ExecutionPolicy Bypass -Command "${titleCommand}"`, { encoding: 'utf8' }, (error: any, stdout: any, stderr: any) => {
                if (error) {
                  reject(error)
                } else {
                  resolve(stdout.trim())
                }
              })
            })
            
            const title = titleOutput || `Chrome Profile ${profile.profileNumber} (运行中)`
            
            runningWindows.push({
              id: hwnd, // 使用实际的窗口句柄
              title: `Chrome Profile ${profile.profileNumber} (运行中)`,
              pid: pid,
              dataDir: profile.dataDir,
              profileNumber: profile.profileNumber,
              isRunning: true,
              shortcutPath: profile.shortcutPath
            })
          } else {
            // 有进程但无窗口句柄
            runningWindows.push({
              id: -profile.profileNumber,
              title: `Chrome Profile ${profile.profileNumber} (运行中)`,
              pid: pid,
              dataDir: profile.dataDir,
              profileNumber: profile.profileNumber,
              isRunning: true,
              shortcutPath: profile.shortcutPath
            })
          }
        } catch (windowError) {
          console.error('获取窗口信息失败:', windowError)
        }
      }
    }
    
    const endTime = Date.now()
    console.log(`找到 ${runningWindows.length} 个运行中的Chrome窗口，耗时: ${endTime - startTime}ms`)
    console.log('返回的窗口数据:', runningWindows)
    return runningWindows
  } catch (error) {
    console.error('获取运行中的Chrome窗口失败:', error)
    return []
  }
}

// get-chrome-windows - 只获取保存的数据（配置文件信息）
ipcMain.handle('get-chrome-windows', async () => {
  try {
    const profiles = await getChromeProfiles()
    
    // 为保存的数据生成标准格式的结果
    const result = profiles.map((profile, index) => ({
      id: -profile.profileNumber,
      number: index + 1,
      title: `Chrome Profile ${profile.profileNumber} (未运行)`,
      pid: 0,
      dataDir: profile.dataDir,
      profileNumber: profile.profileNumber,
      isRunning: false,
      shortcutPath: profile.shortcutPath
    }))
    
    console.log(`成功获取 ${result.length} 个保存的配置文件数据`)
    return result
  } catch (error) {
    console.error('获取Chrome配置文件数据失败:', error)
    return []
  }
})

// get-running-chrome-windows - 获取运行中的窗口信息
ipcMain.handle('get-running-chrome-windows', async () => {
  try {
    // 首先从存储的窗口信息中获取
    const storedWindows = Array.from(windowInfoMap.values())
      .filter(info => info.isRunning)
      .map(info => ({
        id: info.hwnd || info.id, // 优先使用窗口句柄
        title: info.title || `Chrome Profile ${info.profileNumber} (运行中)`,
        pid: info.pid,
        dataDir: info.dataDir,
        profileNumber: info.profileNumber,
        isRunning: true,
        shortcutPath: info.shortcutPath
      }))
    
    console.log(`从存储中获取到 ${storedWindows.length} 个窗口信息`)
    
    // 如果存储的窗口信息足够，直接返回
    if (storedWindows.length > 0) {
      return storedWindows
    }
    
    // 否则回退到原来的方法
  return await getRunningChromeWindows()
  } catch (error) {
    console.error('获取运行中窗口失败:', error)
    return await getRunningChromeWindows()
  }
})

// 查找与指定用户数据目录关联的Chrome进程PID
async function findChromeProcessByUserDataDir(userDataDir: string): Promise<number | null> {
  try {
    // 使用简单的PowerShell命令获取Chrome进程信息
    const command = `powershell -ExecutionPolicy Bypass -Command "Get-Process -Name chrome | Select-Object Id | Format-Table -HideTableHeaders"`;
    
    // 使用异步exec替代execSync，避免阻塞UI
    const output = await new Promise<string>((resolve, reject) => {
      exec(command, { encoding: 'utf8' }, (error: any, stdout: any, stderr: any) => {
        if (error) {
          reject(error)
        } else {
          resolve(stdout)
        }
      })
    })
    
    // 解析输出，获取所有Chrome进程ID
    const lines = output.trim().split('\n');
    
    // 查找包含指定userDataDir的进程
    const normalizedUserDataDir = path.resolve(userDataDir);
    
    // 遍历所有Chrome进程ID
    for (const line of lines) {
      const pidStr = line.trim();
      if (pidStr && !isNaN(parseInt(pidStr, 10))) {
        const pid = parseInt(pidStr, 10);
        try {
          // 使用PowerShell获取特定进程的命令行
          const cmdLineCommand = `powershell -ExecutionPolicy Bypass -Command "Get-WmiObject Win32_Process -Filter 'ProcessId=${pid}' | Select-Object -ExpandProperty CommandLine"`;
          
          // 使用异步exec替代execSync，避免阻塞UI
          const cmdLineOutput = await new Promise<string>((resolve, reject) => {
            exec(cmdLineCommand, { encoding: 'utf8' }, (error: any, stdout: any, stderr: any) => {
              if (error) {
                reject(error)
              } else {
                resolve(stdout.trim())
              }
            })
          })
          
          if (cmdLineOutput) {
            // 使用正则表达式提取--user-data-dir参数值，考虑引号
            const userDataDirMatch = cmdLineOutput.match(/--user-data-dir=(("[^"]+")|[^\s]+)/);
            if (userDataDirMatch && userDataDirMatch[1]) {
              // 去除可能的引号
              let processUserDataDir = userDataDirMatch[1].replace(/^"|"$/g, '');
              // 标准化路径以进行比较
              processUserDataDir = path.resolve(processUserDataDir);
              
              if (processUserDataDir === normalizedUserDataDir) {
                return pid;
              }
            }
          }
        } catch (cmdLineError) {
          // 如果获取特定进程命令行失败，继续处理下一个进程
          continue;
        }
      }
    }
    
    return null
  } catch (error) {
    console.error('查找Chrome进程失败:', error)
    return null
  }
}

// 启动Chrome实例
ipcMain.handle('launch-chrome', async (event, args: { userDataDir: string, port?: number, profileNumber?: number, shortcutPath?: string }) => {
  try {
    const { userDataDir, port, profileNumber = 0, shortcutPath } = args
    
    if (process.platform !== 'win32') {
      return { success: false, error: '仅支持Windows系统' }
    }

    // 检查数据目录是否存在
    if (!fs.existsSync(userDataDir)) {
      return { success: false, error: '数据目录不存在' }
    }

    let pid: number | null = null
    
    // 检查是否存在快捷方式，如果存在则使用快捷方式启动
    if (shortcutPath && fs.existsSync(shortcutPath)) {
      try {
        // 使用PowerShell启动快捷方式
        // 使用异步exec替代execSync，避免阻塞UI
        await new Promise<void>((resolve, reject) => {
          exec(`powershell -ExecutionPolicy Bypass -Command "& '${shortcutPath}'"`, { stdio: 'ignore' }, (error: any, stdout: any, stderr: any) => {
            if (error) {
              reject(error)
            } else {
              resolve()
            }
          })
        })
        
        // 等待一小段时间让进程启动
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // 尝试查找新启动的进程PID
        pid = await findChromeProcessByUserDataDir(userDataDir)
        
        return { 
          success: true, 
          message: '通过快捷方式启动Chrome',
          pid: pid || undefined
        }
      } catch (shortcutError) {
        console.warn('使用快捷方式启动失败，尝试直接启动:', shortcutError)
        // 如果快捷方式启动失败，继续尝试直接启动Chrome
      }
    }

    // 尝试从配置中获取Chrome路径
    const chromePath = store.get('chromePath') as string
    if (!chromePath || !fs.existsSync(chromePath)) {
      // 尝试查找默认路径
      const potentialPaths = [
        path.join(process.env.ProgramFiles || 'C:\\Program Files', 'Google\\Chrome\\Application\\chrome.exe'),
        path.join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'Google\\Chrome\\Application\\chrome.exe'),
        path.join(process.env.LocalAppData || 'C:\\Users\\', process.env.USERNAME || '', 'AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')
      ]
      
      let foundPath = ''
      for (const potentialPath of potentialPaths) {
        if (fs.existsSync(potentialPath)) {
          foundPath = potentialPath
          store.set('chromePath', foundPath) // 保存到配置中
          break
        }
      }
      
      if (!foundPath) {
        return { success: false, error: '找不到Chrome浏览器路径' }
      }
    }

    // 计算调试端口
    const debugPort = port || (9222 + profileNumber)

    // 启动Chrome
    const { spawn } = require('child_process')
    const child = spawn(chromePath, [
      `--user-data-dir=${userDataDir}`,
      `--remote-debugging-port=${debugPort}`,
      '--new-window',
      '--no-first-run',
      '--no-default-browser-check'
    ], { detached: true, stdio: 'ignore' })

    // 直接获取child process的pid
    pid = child.pid
    
    child.unref()
    
    return { 
      success: true, 
      message: 'Chrome已启动',
      pid: pid
    }
  } catch (error) {
    console.error('启动Chrome失败:', error)
    return { success: false, error: String(error) }
  }
})

// 获取屏幕信息
ipcMain.handle('get-screens', () => {
  const displays = screen.getAllDisplays()
  return displays.map(display => ({
    id: display.id,
    x: display.bounds.x,
    y: display.bounds.y,
    width: display.workArea.width,
    height: display.workArea.height,
    primary: display.id === screen.getPrimaryDisplay().id
  }))
})





// 任务队列相关IPC处理器
ipcMain.handle('add-launch-task', async (event, args: { userDataDir: string, port?: number, profileNumber?: number, shortcutPath?: string }) => {
  try {
    if (process.platform !== 'win32') {
      return { success: false, error: '仅支持Windows系统' }
    }

    const taskId = taskQueue.addTask('launch', args)
    return { 
      success: true, 
      message: 'Chrome启动任务已添加到队列',
      taskId: taskId
    }
  } catch (error) {
    console.error('添加启动任务失败:', error)
    return { success: false, error: String(error) }
  }
})

ipcMain.handle('add-close-task', async (event, args: { windowId: number, pid?: number }) => {
  try {
    if (process.platform !== 'win32') {
      return { success: false, error: '仅支持Windows系统' }
    }

    const taskId = taskQueue.addTask('close', args)
    return { 
      success: true, 
      message: 'Chrome关闭任务已添加到队列',
      taskId: taskId
    }
  } catch (error) {
    console.error('添加关闭任务失败:', error)
    return { success: false, error: String(error) }
  }
})

ipcMain.handle('add-arrange-task', async (event, args: { type: string, windowIds: number[], screen: any, direction?: string, margin?: number, params?: any }) => {
  try {
    if (process.platform !== 'win32') {
      return { success: false, error: '仅支持Windows系统' }
    }

    const taskId = taskQueue.addTask('arrange', args)
    return { 
      success: true, 
      message: '窗口排列任务已添加到队列',
      taskId: taskId
    }
  } catch (error) {
    console.error('添加排列任务失败:', error)
    return { success: false, error: String(error) }
  }
})

ipcMain.handle('get-task-status', async (event, taskId: string) => {
  try {
    const task = taskQueue.getTask(taskId)
    if (!task) {
      return { success: false, error: '任务不存在' }
    }
    
    return { 
      success: true, 
      task: task
    }
  } catch (error) {
    console.error('获取任务状态失败:', error)
    return { success: false, error: String(error) }
  }
})

ipcMain.handle('get-all-tasks', async () => {
  try {
    const tasks = taskQueue.getAllTasks()
    return { 
      success: true, 
      tasks: tasks
    }
  } catch (error) {
    console.error('获取所有任务失败:', error)
    return { success: false, error: String(error) }
  }
})

// 防止应用创建多个实例
const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
  // 如果已经有一个实例在运行，则退出新实例
  app.quit()
} else {
  // 监听第二个实例启动事件
  app.on('second-instance', () => {
    // 如果主窗口已存在，则恢复它的焦点
    if (mainWindow) {
      if (mainWindow.isMinimized()) {
        mainWindow.restore()
      }
      mainWindow.focus()
    }
  })
  
  // 确保只在ready事件时创建窗口一次
  app.once('ready', () => {
    createMainWindow()
  })
  
  app.on('window-all-closed', () => {
    if (platform() !== 'darwin') {
      app.quit()
    }
  })
  
  app.on('activate', () => {
    if (mainWindow === null) {
      createMainWindow()
    }
  })
}

// 检查是否有管理员权限（Windows）
ipcMain.handle('check-admin-permission', () => {
  if (platform() !== 'win32') {
    return true // 非Windows平台默认返回true
  }
  
  try {
    // 尝试写入Program Files目录来检查权限
    const testPath = path.join(process.env.ProgramFiles || 'C:\\Program Files', 'chrome-manager-test.txt')
    fs.writeFileSync(testPath, 'test')
    fs.unlinkSync(testPath)
    return true
  } catch {
    return false
  }
})

// 关闭运行中的Chrome窗口
ipcMain.handle('close-running-chrome-window', async (event, windowId: number, pid?: number) => {
  try {
    if (platform() !== 'win32') {
      return { success: false, error: '当前非Windows平台，暂不支持此操作' }
    }
    
    console.log(`尝试关闭窗口，ID: ${windowId}`)
    
    // 处理正ID（有窗口句柄的）和负ID（只有进程的）
    if (windowId > 0) {
      // 有窗口句柄，使用PostMessage关闭窗口
      const powershellCommand = `Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class WindowHelper { [DllImport(\\"user32.dll\\")] public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); }'; $hwnd = [IntPtr]::new(${windowId}); $WM_CLOSE = 0x0010; $success = [WindowHelper]::PostMessage($hwnd, $WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero); @{ Success = $success; WindowId = ${windowId} } | ConvertTo-Json`
      
      // 执行PowerShell命令
      // 使用异步exec替代execSync，避免阻塞UI
      const output = await new Promise<string>((resolve, reject) => {
        exec(`powershell -ExecutionPolicy Bypass -Command "${powershellCommand}"`, { encoding: 'utf8' }, (error: any, stdout: any, stderr: any) => {
          if (error) {
            reject(error)
          } else {
            resolve(stdout)
          }
        })
      })
      console.log(`PowerShell输出: ${output}`)
      const result = JSON.parse(output.trim())
      
      console.log(`尝试关闭窗口 ${windowId}，结果: ${result.Success}`)
      
      return { 
        success: result.Success, 
        error: result.Success ? undefined : '关闭窗口失败' 
      }
    } else if (windowId < 0) {
      // 负ID表示只有进程没有窗口句柄，通过进程ID关闭
      const profileNumber = Math.abs(windowId)
      console.log(`尝试关闭Chrome进程，Profile: ${profileNumber}`)
      
      let targetPid = pid
      
      // 如果没有传入pid，则查找进程ID
      if (!targetPid) {
      const defaultDataDir = store.get('dataDir') || path.join(app.getPath('userData'), 'chrome-environments')
      const dataDir = path.join(defaultDataDir, `Profile_${profileNumber}`)
        const foundPid = await findChromeProcessByUserDataDir(dataDir)
        targetPid = foundPid || undefined
      }
      
      if (targetPid) {
        try {
          // 使用taskkill关闭进程
          // 使用异步exec替代execSync，避免阻塞UI
          await new Promise<void>((resolve, reject) => {
            exec(`taskkill /F /PID ${targetPid}`, { stdio: 'ignore' }, (error: any, stdout: any, stderr: any) => {
              if (error) {
                reject(error)
              } else {
                resolve()
              }
            })
          })
          console.log(`成功关闭Chrome进程，PID: ${targetPid}`)
          // 清理窗口信息
          cleanupWindowInfo(windowId)
          return { success: true, message: `已关闭Chrome进程 ${targetPid}` }
        } catch (killError) {
          console.error('关闭进程失败:', killError)
          return { success: false, error: '关闭进程失败' }
        }
      } else {
        console.log(`未找到Profile ${profileNumber}对应的Chrome进程`)
        return { success: false, error: '未找到对应的Chrome进程' }
      }
    } else {
      return { success: false, error: '无效的窗口ID' }
    }
  } catch (error) {
    console.error('操作Chrome窗口失败:', error)
    return { success: false, error: String(error) }
  }
})

// 窗口信息存储
interface WindowInfo {
  id: number
  pid: number
  hwnd?: number  // 窗口句柄，可能暂时没有
  title?: string
  dataDir: string
  profileNumber: number
  isRunning: boolean
  shortcutPath?: string
  launchTime: number
}

// 使用PowerShell移动窗口（简化版本）
async function moveWindowWithAPI(hwnd: number, x: number, y: number, width: number, height: number): Promise<boolean> {
  try {
    console.log(`尝试移动窗口 ${hwnd} 到 (${x}, ${y}) 大小 ${width}x${height}`)

    if (platform() !== 'win32') {
      console.log('当前非Windows平台，无法移动窗口')
      return false
    }

    // 使用简化的PowerShell命令
    const command = `powershell -ExecutionPolicy Bypass -Command "Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class Win32 { [DllImport(\\"user32.dll\\")] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); [DllImport(\\"user32.dll\\")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); }'; $hwnd = [IntPtr]::new(${hwnd}); [Win32]::ShowWindow($hwnd, 9); [Win32]::MoveWindow($hwnd, ${x}, ${y}, ${width}, ${height}, $true)"`
    
    // 使用异步exec替代execSync，避免阻塞UI
    const output = await new Promise<string>((resolve, reject) => {
      exec(command, { encoding: 'utf8', timeout: 5000 }, (error: any, stdout: any, stderr: any) => {
        if (error) {
          reject(error)
        } else {
          resolve(stdout)
        }
      })
    })
    console.log(`PowerShell输出: ${output}`)
    
    return true
  } catch (error) {
    console.error('使用PowerShell移动窗口失败:', error)
    return false
  }
}

// 全局窗口信息存储
const windowInfoMap = new Map<number, WindowInfo>()

// 任务队列系统
interface Task {
  id: string
  type: 'launch' | 'close' | 'arrange' | 'find-handle'
  data: any
  status: 'pending' | 'running' | 'completed' | 'failed'
  progress: number
  result?: any
  error?: string
  startTime?: number
  endTime?: number
}

class TaskQueue {
  private tasks = new Map<string, Task>()
  private runningTasks = new Set<string>()
  private maxConcurrent = 5 // 最大并发任务数（增加以支持句柄查找任务）

  addTask(type: Task['type'], data: any): string {
    const id = `${type}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    const task: Task = {
      id,
      type,
      data,
      status: 'pending',
      progress: 0
    }
    
    this.tasks.set(id, task)
    this.processQueue()
    
    return id
  }

  getTask(id: string): Task | undefined {
    return this.tasks.get(id)
  }

  getAllTasks(): Task[] {
    return Array.from(this.tasks.values())
  }

  private async processQueue() {
    if (this.runningTasks.size >= this.maxConcurrent) {
      return
    }

    const pendingTasks = Array.from(this.tasks.values())
      .filter(task => task.status === 'pending')
      .sort((a, b) => a.startTime || 0 - (b.startTime || 0))

    for (const task of pendingTasks) {
      if (this.runningTasks.size >= this.maxConcurrent) {
        break
      }

      this.runningTasks.add(task.id)
      task.status = 'running'
      task.startTime = Date.now()
      task.progress = 0

      // 异步执行任务
      this.executeTask(task).catch(error => {
        console.error(`任务 ${task.id} 执行失败:`, error)
        task.status = 'failed'
        task.error = String(error)
        task.endTime = Date.now()
        this.runningTasks.delete(task.id)
      })
    }
  }

  private async executeTask(task: Task) {
    try {
      let result: any

      switch (task.type) {
        case 'launch':
          result = await this.executeLaunchTask(task)
          break
        case 'close':
          result = await this.executeCloseTask(task)
          break
        case 'arrange':
          result = await this.executeArrangeTask(task)
          break
        case 'find-handle':
          result = await this.executeFindHandleTask(task)
          break
        default:
          throw new Error(`未知任务类型: ${task.type}`)
      }

      task.status = 'completed'
      task.result = result
      task.progress = 100
      task.endTime = Date.now()
      
      // 通知前端任务完成
      if (mainWindow) {
        mainWindow.webContents.send('task-completed', {
          id: task.id,
          type: task.type,
          status: task.status,
          result: result
        })
      }

    } catch (error) {
      task.status = 'failed'
      task.error = String(error)
      task.endTime = Date.now()
      
      // 通知前端任务失败
      if (mainWindow) {
        mainWindow.webContents.send('task-failed', {
          id: task.id,
          type: task.type,
          status: task.status,
          error: String(error)
        })
      }
    } finally {
      this.runningTasks.delete(task.id)
      // 继续处理队列中的其他任务
      this.processQueue()
    }
  }

  private async executeLaunchTask(task: Task): Promise<any> {
    const { userDataDir, port, profileNumber, shortcutPath } = task.data
    
    task.progress = 10
    
    // 检查数据目录是否存在
    if (!fs.existsSync(userDataDir)) {
      throw new Error('数据目录不存在')
    }

    task.progress = 20

    let pid: number | null = null
    
    // 检查是否存在快捷方式
    if (shortcutPath && fs.existsSync(shortcutPath)) {
      try {
        // 使用异步exec替代execSync，避免阻塞UI
        await new Promise<void>((resolve, reject) => {
          exec(`powershell -ExecutionPolicy Bypass -Command "& '${shortcutPath}'"`, { stdio: 'ignore' }, (error: any, stdout: any, stderr: any) => {
            if (error) {
              reject(error)
            } else {
              resolve()
            }
          })
        })
        await new Promise(resolve => setTimeout(resolve, 500))
        pid = await findChromeProcessByUserDataDir(userDataDir)
        task.progress = 80
        return { 
          success: true, 
          message: '通过快捷方式启动Chrome',
          pid: pid || undefined
        }
      } catch (shortcutError) {
        console.warn('使用快捷方式启动失败，尝试直接启动:', shortcutError)
      }
    }

    task.progress = 30

    // 获取Chrome路径
    const chromePath = store.get('chromePath') as string
    if (!chromePath || !fs.existsSync(chromePath)) {
        const potentialPaths = [
          path.join(process.env.ProgramFiles || 'C:\\Program Files', 'Google\\Chrome\\Application\\chrome.exe'),
          path.join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'Google\\Chrome\\Application\\chrome.exe'),
          path.join(process.env.LocalAppData || 'C:\\Users\\', process.env.USERNAME || '', 'AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')
        ]
        
      let foundPath = ''
        for (const potentialPath of potentialPaths) {
          if (fs.existsSync(potentialPath)) {
          foundPath = potentialPath
          store.set('chromePath', foundPath)
            break
          }
        }
      
      if (!foundPath) {
        throw new Error('找不到Chrome浏览器路径')
      }
    }

    task.progress = 50

    // 启动Chrome
    const debugPort = port || (9222 + profileNumber)
    const { spawn } = require('child_process')
    const child = spawn(chromePath, [
      `--user-data-dir=${userDataDir}`,
      `--remote-debugging-port=${debugPort}`,
      '--new-window',
      '--no-first-run',
      '--no-default-browser-check'
    ], { detached: true, stdio: 'ignore' })

    pid = child.pid || 0
    child.unref()
    
    task.progress = 70

    // 创建窗口信息并存储
    const windowInfo: WindowInfo = {
      id: -profileNumber,
      pid: pid || 0,
      dataDir: userDataDir,
      profileNumber: profileNumber,
      isRunning: true,
      launchTime: Date.now()
    }
    
    windowInfoMap.set(-profileNumber, windowInfo)
    
    task.progress = 90

    // 延迟获取窗口句柄 - 使用任务队列异步执行
    if (pid && pid > 0) {
      setTimeout(() => {
        // 添加句柄查找任务到队列
        taskQueue.addTask('find-handle', {
          pid: pid,
          profileNumber: profileNumber
        })
      }, 2000)
    }

    return { 
      success: true, 
      message: 'Chrome已启动',
      pid: pid
    }
  }

  private async executeCloseTask(task: Task): Promise<any> {
    const { windowId, pid } = task.data
    
    task.progress = 10

    if (windowId > 0) {
      // 有窗口句柄，使用PostMessage关闭窗口
      const powershellCommand = `Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public class WindowHelper { [DllImport(\\"user32.dll\\")] public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); }'; $hwnd = [IntPtr]::new(${windowId}); $WM_CLOSE = 0x0010; $success = [WindowHelper]::PostMessage($hwnd, $WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero); @{ Success = $success; WindowId = ${windowId} } | ConvertTo-Json`
      
      task.progress = 30
      
      // 使用异步exec替代execSync，避免阻塞UI
      const output = await new Promise<string>((resolve, reject) => {
        exec(`powershell -ExecutionPolicy Bypass -Command "${powershellCommand}"`, { encoding: 'utf8' }, (error: any, stdout: any, stderr: any) => {
          if (error) {
            reject(error)
          } else {
            resolve(stdout)
          }
        })
      })
      const result = JSON.parse(output.trim())
      
      task.progress = 80
      
      if (result.Success) {
        cleanupWindowInfo(windowId)
      }
      
      return { 
        success: result.Success, 
        error: result.Success ? undefined : '关闭窗口失败' 
      }
    } else if (windowId < 0) {
      // 负ID表示只有进程没有窗口句柄
      const profileNumber = Math.abs(windowId)
      
      task.progress = 30
      
      let targetPid = pid
      if (!targetPid) {
        const defaultDataDir = store.get('dataDir') || path.join(app.getPath('userData'), 'chrome-environments')
        const dataDir = path.join(defaultDataDir, `Profile_${profileNumber}`)
        const foundPid = await findChromeProcessByUserDataDir(dataDir)
        targetPid = foundPid || undefined
      }
      
      task.progress = 60
      
      if (targetPid) {
        // 使用异步exec替代execSync，避免阻塞UI
        await new Promise<void>((resolve, reject) => {
          exec(`taskkill /F /PID ${targetPid}`, { stdio: 'ignore' }, (error: any, stdout: any, stderr: any) => {
            if (error) {
              reject(error)
            } else {
              resolve()
            }
          })
        })
        cleanupWindowInfo(windowId)
        task.progress = 90
        return { success: true, message: `已关闭Chrome进程 ${targetPid}` }
      } else {
        throw new Error('未找到对应的Chrome进程')
      }
    } else {
      throw new Error('无效的窗口ID')
    }
  }

  private async executeArrangeTask(task: Task): Promise<any> {
    const { type, windowIds, screen, direction, margin, params } = task.data
    
    task.progress = 10

    if (type === 'auto') {
      return await this.executeAutoArrange(task, windowIds, screen, direction, margin)
    } else if (type === 'custom') {
      return await this.executeCustomArrange(task, windowIds, screen, params)
    } else {
      throw new Error('不支持的排列类型')
    }
  }

  private async executeAutoArrange(task: Task, windowIds: number[], screen: any, direction: string, margin: number): Promise<any> {
    const screenWidth = screen.workArea.width
    const screenHeight = screen.workArea.height
    const screenX = screen.workArea.x
    const screenY = screen.workArea.y
    
    task.progress = 20

    const count = windowIds.length
    const cols = Math.ceil(Math.sqrt(count))
    const rows = Math.ceil(count / cols)
    
    const windowWidth = Math.floor((screenWidth - margin * (cols + 1)) / cols)
    const windowHeight = Math.floor((screenHeight - margin * (rows + 1)) / rows)
    
    task.progress = 40

    const positions = []
    for (let i = 0; i < count; i++) {
      const row = Math.floor(i / cols)
      const col = i % cols
      const x = screenX + margin + col * (windowWidth + margin)
      const y = screenY + margin + row * (windowHeight + margin)
      positions.push({ x, y, width: windowWidth, height: windowHeight })
    }
    
    task.progress = 60

    let successCount = 0
    const totalWindows = windowIds.length
    
    for (let i = 0; i < windowIds.length; i++) {
      const windowId = windowIds[i]
      const position = positions[i]
      
      try {
        const success = await moveWindowWithAPI(windowId, position.x, position.y, position.width, position.height)
        if (success) {
          successCount++
        }
      } catch (error) {
        console.error(`移动窗口 ${windowId} 失败:`, error)
      }
      
      // 更新进度
      task.progress = 60 + Math.floor((i + 1) / totalWindows * 30)
    }
    
    task.progress = 100
    
    return { 
      success: successCount > 0, 
      message: `成功排列 ${successCount}/${windowIds.length} 个窗口`,
      arrangedCount: successCount
    }
  }

  private async executeCustomArrange(task: Task, windowIds: number[], screen: any, params: any): Promise<any> {
    const { startX, startY, windowWidth, windowHeight, hSpacing, vSpacing, windowsPerRow } = params
    
    task.progress = 20

    let successCount = 0
    const totalWindows = windowIds.length
    
    for (let i = 0; i < windowIds.length; i++) {
      const windowId = windowIds[i]
      const row = Math.floor(i / windowsPerRow)
      const col = i % windowsPerRow
      
      const x = startX + col * (windowWidth + hSpacing)
      const y = startY + row * (windowHeight + vSpacing)
      
      try {
        const success = await moveWindowWithAPI(windowId, x, y, windowWidth, windowHeight)
        if (success) {
          successCount++
        }
      } catch (error) {
        console.error(`移动窗口 ${windowId} 失败:`, error)
      }
      
      // 更新进度
      task.progress = 20 + Math.floor((i + 1) / totalWindows * 70)
    }
    
    task.progress = 100
    
    return { 
      success: successCount > 0, 
      message: `成功排列 ${successCount}/${windowIds.length} 个窗口`,
      arrangedCount: successCount
    }
  }

  private async executeFindHandleTask(task: Task): Promise<any> {
    const { pid, profileNumber } = task.data
    
    task.progress = 10

    try {
      console.log(`异步查找PID ${pid} 的窗口句柄...`)
      const windowHandle = await findWindowHandleByPid(pid)
      
      task.progress = 50
      
      if (windowHandle) {
        const existingInfo = windowInfoMap.get(-profileNumber)
        if (existingInfo) {
          existingInfo.hwnd = windowHandle.hwnd
          existingInfo.title = windowHandle.title
          existingInfo.id = windowHandle.hwnd
          windowInfoMap.set(windowHandle.hwnd, existingInfo)
          windowInfoMap.delete(-profileNumber)
          
          console.log(`异步成功获取窗口句柄 ${windowHandle.hwnd}，标题: ${windowHandle.title}`)
        }
        
        task.progress = 100
        
        return {
          success: true,
          message: `成功获取窗口句柄 ${windowHandle.hwnd}`,
          hwnd: windowHandle.hwnd,
          title: windowHandle.title
        }
      } else {
        task.progress = 100
        
        return {
          success: false,
          message: `PID ${pid} 未找到可见窗口`
        }
      }
    } catch (error) {
      console.error(`异步获取窗口句柄失败:`, error)
      task.progress = 100
      
      return {
        success: false,
        error: String(error)
      }
    }
  }
}

// 创建全局任务队列实例
const taskQueue = new TaskQueue()

// 清理窗口信息
function cleanupWindowInfo(windowId: number) {
  // 删除存储的窗口信息
  windowInfoMap.delete(windowId)
  
  // 如果是负数ID，也尝试删除对应的正数ID条目
  if (windowId < 0) {
    const profileNumber = Math.abs(windowId)
    const entries = Array.from(windowInfoMap.entries())
    for (const [id, info] of entries) {
      if (info.profileNumber === profileNumber) {
        windowInfoMap.delete(id)
            break
      }
    }
  }
}

// 根据PID查找窗口句柄
async function findWindowHandleByPid(pid: number): Promise<{ hwnd: number, title: string } | null> {
  try {
    console.log(`开始查找PID ${pid} 的窗口句柄...`)
    
    // 使用简化的PowerShell命令，通过进程ID查找窗口
    const simpleCommand = `Get-Process -Id ${pid} | Select-Object Id, ProcessName, MainWindowTitle | ConvertTo-Json`
    
    // 使用异步exec替代execSync，避免阻塞UI
    const output = await new Promise<string>((resolve, reject) => {
      exec(`powershell -ExecutionPolicy Bypass -Command "${simpleCommand}"`, { encoding: 'utf8' }, (error: any, stdout: any, stderr: any) => {
        if (error) {
          reject(error)
        } else {
          resolve(stdout.trim())
        }
      })
    })
    
    console.log(`PowerShell输出: ${output}`)
    
    if (output && output !== '') {
      try {
        const processInfo = JSON.parse(output)
        console.log(`找到进程: ID=${processInfo.Id}, 名称=${processInfo.ProcessName}, 窗口标题=${processInfo.MainWindowTitle}`)
        
        // 检查是否有窗口标题
        if (processInfo.MainWindowTitle && processInfo.MainWindowTitle.trim() !== '') {
          // 使用更简单的方法，通过进程ID直接获取主窗口句柄
          const hwndCommand = `Get-Process -Id ${pid} | Select-Object -ExpandProperty MainWindowHandle`
          
          // 使用异步exec替代execSync
          const hwndOutput = await new Promise<string>((resolve, reject) => {
            exec(`powershell -ExecutionPolicy Bypass -Command "${hwndCommand}"`, { encoding: 'utf8' }, (error: any, stdout: any, stderr: any) => {
              if (error) {
                reject(error)
              } else {
                resolve(stdout.trim())
              }
            })
          })
          
          const hwnd = parseInt(hwndOutput) || 0
          
          if (hwnd > 0) {
            return {
              hwnd: hwnd,
              title: processInfo.MainWindowTitle
            }
          }
        }
        
        console.log(`PID ${pid} 没有找到可见窗口`)
        return null
      } catch (parseError: any) {
        console.error(`解析PID ${pid} 的进程信息失败:`, parseError)
        console.log(`原始输出: ${output}`)
        return null
      }
    } else {
      console.log(`PID ${pid} 没有找到进程`)
      return null
    }
  } catch (error) {
    console.error(`查找PID ${pid} 的窗口句柄失败:`, error)
    return null
  }
}

// 启动Chrome配置文件
ipcMain.handle('launch-chrome-profile', async (event, windowId: number) => {
  try {
    if (platform() !== 'win32') {
      return { success: false, error: '当前非Windows平台，暂不支持此操作' }
    }
    
    // 只处理负ID（非运行状态的配置文件）
    if (windowId >= 0) {
      return { success: false, error: '无效的配置文件ID' }
    }
    
    const profileNumber = Math.abs(windowId)
    const defaultDataDir = store.get('dataDir') || path.join(app.getPath('userData'), 'chrome-environments')
    const dataDir = path.join(defaultDataDir, `Profile_${profileNumber}`)
    
    // 先从store获取chromePath
    let chromePath = store.get('chromePath')
      
      // 如果仍然没有有效的chromePath，返回错误
      if (!chromePath || !fs.existsSync(chromePath)) {
        console.log("无法找到有效的Chrome可执行文件路径")
        return { success: false, error: 'Chrome可执行文件路径未设置或无效，请手动指定Chrome安装位置' }
      }
      
      if (!fs.existsSync(dataDir)) {
        return { success: false, error: `配置文件目录不存在: ${dataDir}` }
      }
      
      console.log(`启动Chrome配置文件 ${profileNumber}`)
      
    // 直接启动Chrome进程，不创建快捷方式
    const { spawn } = require('child_process')
    const child = spawn(chromePath, [
      `--user-data-dir=${dataDir}`,
      `--remote-debugging-port=${9222 + profileNumber}`,
      '--no-first-run',
      '--no-default-browser-check',
      '--new-window'
    ], { 
      detached: true, 
      stdio: 'ignore'
    })
    
    // 获取进程ID
    const pid = child.pid
    child.unref()
    
    console.log(`已直接启动Chrome配置文件 ${profileNumber}，PID: ${pid}`)
    
    // 创建窗口信息并存储
    const windowInfo: WindowInfo = {
      id: -profileNumber, // 使用负数ID作为配置文件ID
      pid: pid,
      dataDir: dataDir,
      profileNumber: profileNumber,
      isRunning: true,
      launchTime: Date.now()
    }
    
    // 存储窗口信息
    windowInfoMap.set(-profileNumber, windowInfo)
    
    // 延迟获取窗口句柄 - 使用任务队列异步执行
    setTimeout(() => {
      // 添加句柄查找任务到队列
      taskQueue.addTask('find-handle', {
        pid: pid,
        profileNumber: profileNumber
      })
    }, 3000) // 3秒后开始第一次尝试
    
    return { 
      success: true, 
      message: `已启动Chrome配置文件 ${profileNumber}`,
      pid: pid
    }
  } catch (error) {
    console.error('启动Chrome配置文件失败:', error)
    return { success: false, error: String(error) }
  }
})

// 自动排列窗口
async function autoArrangeWindows(windowIds: number[], screen: any, direction: string, margin: number) {
  try {
    console.log(`自动排列 ${windowIds.length} 个窗口`)
    
    // 获取屏幕工作区尺寸
    const screenWidth = screen.workArea.width
    const screenHeight = screen.workArea.height
    const screenX = screen.workArea.x
    const screenY = screen.workArea.y
    
    console.log(`屏幕工作区: ${screenWidth}x${screenHeight} at (${screenX}, ${screenY})`)
    
    // 计算最佳布局（参考Python代码的算法）
    const count = windowIds.length
    const cols = Math.ceil(Math.sqrt(count))
    const rows = Math.ceil(count / cols)
    
    // 计算窗口大小（考虑边距）
    const windowWidth = Math.floor((screenWidth - margin * (cols + 1)) / cols)
    const windowHeight = Math.floor((screenHeight - margin * (rows + 1)) / rows)
    
    console.log(`布局: ${rows}行 x ${cols}列, 窗口大小: ${windowWidth}x${windowHeight}`)
    
    // 创建位置映射
    const positions = []
    for (let i = 0; i < count; i++) {
      const row = Math.floor(i / cols)
      const col = i % cols
      const x = screenX + margin + col * (windowWidth + margin)
      const y = screenY + margin + row * (windowHeight + margin)
      positions.push({ x, y, width: windowWidth, height: windowHeight })
    }
    
    // 应用窗口位置
    let successCount = 0
    for (let i = 0; i < windowIds.length; i++) {
      const windowId = windowIds[i]
      const position = positions[i]
      
      try {
        // 使用Windows API移动窗口
        console.log(`使用Windows API移动窗口 ${windowId} 到 (${position.x}, ${position.y})`)
        const success = await moveWindowWithAPI(windowId, position.x, position.y, position.width, position.height)
        
        if (success) {
          successCount++
          console.log(`窗口 ${windowId} 移动成功到 (${position.x}, ${position.y})`)
        } else {
          console.log(`窗口 ${windowId} 移动失败`)
        }
      } catch (error) {
        console.error(`移动窗口 ${windowId} 失败:`, error)
      }
    }
    
    console.log(`成功排列 ${successCount}/${windowIds.length} 个窗口`)
    return { 
      success: successCount > 0, 
      message: `成功排列 ${successCount}/${windowIds.length} 个窗口`,
      arrangedCount: successCount
    }
  } catch (error) {
    console.error('自动排列窗口失败:', error)
    return { success: false, error: String(error) }
  }
}

// 自定义排列窗口
async function customArrangeWindows(windowIds: number[], params: any, screen: any) {
  try {
    console.log(`自定义排列 ${windowIds.length} 个窗口`)
    
    const { startX, startY, windowWidth, windowHeight, hSpacing, vSpacing, windowsPerRow } = params
    
    let successCount = 0
    for (let i = 0; i < windowIds.length; i++) {
      const windowId = windowIds[i]
      const row = Math.floor(i / windowsPerRow)
      const col = i % windowsPerRow
      
      const x = startX + col * (windowWidth + hSpacing)
      const y = startY + row * (windowHeight + vSpacing)
      
      try {
        // 使用Windows API移动窗口
        console.log(`使用Windows API移动窗口 ${windowId} 到 (${x}, ${y})`)
        const success = await moveWindowWithAPI(windowId, x, y, windowWidth, windowHeight)
        
        if (success) {
          successCount++
          console.log(`窗口 ${windowId} 移动成功到 (${x}, ${y})`)
        } else {
          console.log(`窗口 ${windowId} 移动失败`)
        }
      } catch (error) {
        console.error(`移动窗口 ${windowId} 失败:`, error)
      }
    }
    
    console.log(`成功排列 ${successCount}/${windowIds.length} 个窗口`)
    return { 
      success: successCount > 0, 
      message: `成功排列 ${successCount}/${windowIds.length} 个窗口`,
      arrangedCount: successCount
    }
  } catch (error) {
    console.error('自定义排列窗口失败:', error)
    return { success: false, error: String(error) }
  }
}

// 窗口排列
ipcMain.handle('arrange-windows', async (event, params: any) => {
  try {
    if (platform() !== 'win32') {
      return { success: false, error: '当前非Windows平台，暂不支持窗口排列' }
    }

    console.log('开始排列窗口，参数:', params)

    const { type, screenId, direction, margin, windowIds } = params

    if (!windowIds || windowIds.length === 0) {
      return { success: false, error: '没有选择要排列的窗口' }
    }

    // 获取屏幕信息
    const displays = screen.getAllDisplays()
    const screens = displays.map(display => ({
      id: display.id,
      x: display.bounds.x,
      y: display.bounds.y,
      width: display.bounds.width,
      height: display.bounds.height,
      primary: display.id === screen.getPrimaryDisplay().id,
      workArea: {
        x: display.workArea.x,
        y: display.workArea.y,
        width: display.workArea.width,
        height: display.workArea.height
      }
    }))
    
    if (!screens || screens.length === 0) {
      return { success: false, error: '无法获取屏幕信息' }
    }

    const targetScreen = screens[screenId] || screens[0]
    console.log('目标屏幕:', targetScreen)

    // 过滤出有效的窗口句柄（正数ID）
    const validWindowIds = windowIds.filter((id: number) => id > 0)
    
    if (validWindowIds.length === 0) {
      return { success: false, error: '没有运行中的窗口可以排列，请先启动Chrome窗口' }
    }
    
    console.log(`有效窗口句柄: ${validWindowIds}`)
    
    if (type === 'auto') {
      return await autoArrangeWindows(validWindowIds, targetScreen, direction, margin)
    } else if (type === 'custom') {
      return await customArrangeWindows(validWindowIds, params, targetScreen)
    } else {
      return { success: false, error: '不支持的排列类型' }
    }
  } catch (error) {
    console.error('排列窗口失败:', error)
    return { success: false, error: String(error) }
  }
})

// 同步控制
ipcMain.handle('start-sync', async (event, windowIds: number[]) => {
  try {
    // 这里将在后续实现
    return { success: true }
  } catch (error) {
    console.error('开始同步失败:', error)
    return { success: false, error: String(error) }
  }
})

ipcMain.handle('stop-sync', async () => {
  try {
    // 这里将在后续实现
    return { success: true }
  } catch (error) {
    console.error('停止同步失败:', error)
    return { success: false, error: String(error) }
  }
})

// 创建快捷方式
ipcMain.handle('create-shortcut', async (event, options: { target: string, args: string, name: string, icon?: string }) => {
  try {
    // 这里将在后续实现
    return { success: true }
  } catch (error) {
    console.error('创建快捷方式失败:', error)
    return { success: false, error: String(error) }
  }
})

// 以管理员权限重启
ipcMain.handle('restart-as-admin', async () => {
  try {
    // 这里将在后续实现
    return { success: true }
  } catch (error) {
    console.error('以管理员权限重启失败:', error)
    return { success: false, error: String(error) }
  }
})

// 设置相关
ipcMain.handle('get-settings', () => {
  return store.store
})

ipcMain.handle('save-settings', (event, settings: any) => {
  try {
    Object.assign(store.store, settings)
    return { success: true }
  } catch (error) {
    console.error('保存设置失败:', error)
    return { success: false, error: String(error) }
  }
})

// 退出应用
ipcMain.handle('quit-app', () => {
  app.quit()
  return { success: true }
})

// 选择Chrome可执行文件
ipcMain.handle('select-chrome-executable', async () => {
  const { dialog } = require('electron')
  try {
    const result = await dialog.showOpenDialog(mainWindow!, {
      title: '选择Chrome可执行文件',
      properties: ['openFile'],
      filters: [
        { name: '可执行文件', extensions: ['exe'] },
        { name: '所有文件', extensions: ['*'] }
      ]
    })
    
    if (!result.canceled && result.filePaths.length > 0) {
      return result.filePaths[0]
    }
    return null
  } catch (error) {
    console.error('选择Chrome可执行文件失败:', error)
    return null
  }
})

// 选择目录
ipcMain.handle('select-directory', async () => {
  const { dialog } = require('electron')
  try {
    const result = await dialog.showOpenDialog(mainWindow!, {
      title: '选择目录',
      properties: ['openDirectory']
    })
    
    if (!result.canceled && result.filePaths.length > 0) {
      return result.filePaths[0]
    }
    return null
  } catch (error) {
    console.error('选择目录失败:', error)
    return null
  }
})

// 获取默认路径
ipcMain.handle('get-default-paths', () => {
  const appData = app.getPath('appData')
  const userData = app.getPath('userData')
  const tempDir = app.getPath('temp')
  const desktopDir = app.getPath('desktop')
  
  // 尝试查找默认的Chrome安装路径（Windows系统）
  let defaultChromePath = ''
  if (platform() === 'win32') {
    const potentialPaths = [
      path.join(process.env.ProgramFiles || 'C:\\Program Files', 'Google\\Chrome\\Application\\chrome.exe'),
      path.join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'Google\\Chrome\\Application\\chrome.exe'),
      path.join(process.env.LocalAppData || 'C:\\Users\\', process.env.USERNAME || '', 'AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')
    ]
    
    // 检查哪个路径存在
    for (const chromePath of potentialPaths) {
      if (fs.existsSync(chromePath)) {
        defaultChromePath = chromePath
        break
      }
    }
  }
  
  // 应用数据目录（用于保存Chrome用户数据）
  const defaultDataDir = path.join(userData, 'chrome-environments')
  
  // 快捷方式保存目录（默认为桌面）
  const defaultShortcutDir = desktopDir
  
  return {
    chromePath: defaultChromePath,
    dataDir: defaultDataDir,
    shortcutDir: defaultShortcutDir,
    tempDir: tempDir
  }
})

// 创建Chrome环境
ipcMain.handle('create-chrome-environment', async (event, config) => {
  try {
    const { chromePath, dataDir, debugPort, createDesktopShortcut, profileNumber } = config
    
    // 确保数据目录存在
    if (!fs.existsSync(dataDir)) {
      fs.mkdirSync(dataDir, { recursive: true })
      console.log(`创建数据目录: ${dataDir}`)
    }
    
    // 初始化Chrome配置文件
    const defaultPrefs = {
      profile: {
        default_content_settings: {
          cookies: 1,
          images: 1,
          javascript: 1,
          plugins: 1,
          popups: 1,
          geolocation: 0,
          notifications: 0
        },
        default_content_setting_values: {
          camera: 2,
          microphone: 2,
          midi_sysex: 0
        },
        name: `Profile ${profileNumber}`,
        avatar_index: profileNumber % 8 // 使用不同的头像索引
      },
      browser: {
        check_default_browser: false
      },
      homepage: 'about:blank',
      startup_urls: ['about:blank']
    }
    
    // 创建必要的目录结构
    const prefsDir = path.join(dataDir, 'Default')
    if (!fs.existsSync(prefsDir)) {
      fs.mkdirSync(prefsDir, { recursive: true })
    }
    
    // 写入默认首选项文件
    const prefsPath = path.join(prefsDir, 'Preferences')
    fs.writeFileSync(prefsPath, JSON.stringify(defaultPrefs, null, 2), 'utf-8')
    console.log(`创建默认首选项文件: ${prefsPath}`)
    
    // 创建Local State文件
    const localState = {
      browser: {
        last_redirect_origin_mapping: {},
        show_home_button: true
      },
      profile: {
        last_used: 'Default'
      }
    }
    const localStatePath = path.join(dataDir, 'Local State')
    fs.writeFileSync(localStatePath, JSON.stringify(localState, null, 2), 'utf-8')
    console.log(`创建Local State文件: ${localStatePath}`)
    
    // 构建快捷方式目标
    const target = chromePath
    const args = [
      `--user-data-dir=${dataDir}`,
      `--remote-debugging-port=${debugPort}`,
      '--no-first-run',
      '--no-default-browser-check'
    ]
    const argsString = args.join(' ')
    
    // 创建快捷方式的函数
    const createShortcut = async (shortcutPath: string) => {
      try {
        // 使用Electron的shell模块创建快捷方式
        const shell = require('electron').shell
        
        // 对于Windows，我们使用Node.js的子进程来创建快捷方式
        if (process.platform === 'win32') {
          const wscriptPath = path.join(process.env.WINDIR || 'C:\\Windows', 'System32', 'wscript.exe')
          const tempVbsPath = path.join(app.getPath('temp'), `create_shortcut_${Date.now()}.vbs`)
          
          // 创建VBS脚本内容
          const vbsContent = `
            Set objShell = CreateObject("WScript.Shell")
            Set objShortcut = objShell.CreateShortcut("${shortcutPath.replace(/\\/g, '\\\\')}")
            objShortcut.TargetPath = "${target.replace(/\\/g, '\\\\')}"
            objShortcut.Arguments = "${argsString.replace(/"/g, '\"')}"
            objShortcut.Description = "Chrome Profile ${profileNumber}"
            objShortcut.WorkingDirectory = "${path.dirname(target).replace(/\\/g, '\\\\')}"
            objShortcut.IconLocation = "${target.replace(/\\/g, '\\\\')},0"
            objShortcut.Save
          `
          
          // 写入临时VBS脚本
          fs.writeFileSync(tempVbsPath, vbsContent, 'utf-8')
          
          // 执行VBS脚本来创建快捷方式
          // 使用异步exec替代execSync，避免阻塞UI
          await new Promise<void>((resolve, reject) => {
            exec(`${wscriptPath} ${tempVbsPath}`, { stdio: 'ignore' }, (error: any, stdout: any, stderr: any) => {
              if (error) {
                reject(error)
              } else {
                resolve()
              }
            })
          })
          
          // 删除临时VBS脚本
          fs.unlinkSync(tempVbsPath)
          
          console.log(`成功创建快捷方式: ${shortcutPath}`)
        } else {
          console.log(`当前平台 ${process.platform} 暂不支持创建快捷方式`)
        }
      } catch (error) {
        console.error(`创建快捷方式失败 ${shortcutPath}:`, error)
        throw error
      }
    }
    
    // 1. 在用户数据目录中创建快捷方式
    const dataDirShortcutPath = path.join(dataDir, `Chrome Profile ${profileNumber}.lnk`)
    await createShortcut(dataDirShortcutPath)
    
    // 2. 如果需要，同时创建桌面快捷方式
    if (createDesktopShortcut) {
      const desktopPath = app.getPath('desktop')
      const desktopShortcutPath = path.join(desktopPath, `Chrome Profile ${profileNumber}.lnk`)
      await createShortcut(desktopShortcutPath)
    }
    
    return { success: true, profileNumber }
  } catch (error) {
    console.error('创建Chrome环境失败:', error)
    throw new Error(`创建Chrome环境失败: ${error instanceof Error ? error.message : String(error)}`)
  }
})